<?php
/* 
    Name：FastPHP
    CopyRight: Mr.Fu 2019SR0832915
*/
namespace app\base;
/*
    概率计算类
    Author:FastPHP
*/
class Lottery
{
    static public function lottery($prize_arr)
    {
        // $prize_arr = array(   
        //     '0' => array('id'=>1,'prize'=>'MAC','rate'=>10),   
        //     '1' => array('id'=>2,'prize'=>'iPhone','rate'=>10),   
        //     '2' => array('id'=>3,'prize'=>'iPad','rate'=>20),   
        //     '3' => array('id'=>4,'prize'=>'iWatch','rate'=>60),   
        //     '4' => array('id'=>5,'prize'=>'iPod','rate'=>100),   
        //     '5' => array('id'=>6,'prize'=>'抱歉!再接再厉','rate'=>1800),
        // );
        
        foreach ($prize_arr as $key => $val) {   
            $arr[$val['id']] = $val['rate'];   
        }
        $rid = self::get_rand($arr); //根据概率获取奖项id   
        
        $res['winning'] = $prize_arr[$rid-1]; //中奖项   
        unset($prize_arr[$rid-1]); //将中奖项从数组中剔除，剩下未中奖项   
        shuffle($prize_arr); //打乱数组顺序   
        for($i=0;$i<count($prize_arr);$i++){   
            $pr[] = $prize_arr[$i];   
        }
        $res['no'] = $pr;   //未中奖项  
        return $res;
    }

    static public function get_rand($proArr){        
        $result = ''; 
        //概率数组的总概率精度
        $proSum = array_sum($proArr); 
        //概率数组循环
        foreach ($proArr as $key => $proCur) { 
            $randNum = mt_rand(1, $proSum);             
            if ($randNum <= $proCur) { 
                $result = $key;                       
                break; 
            } else { 
                $proSum -= $proCur;                     
            } 
        } 
        unset ($proArr); 
        return $result; 
    }
}